#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

#include <minigui/common.h>

#include "command.h"
#include "common.h"
#include "message.h"

extern int qid_snd;
extern int qid_rcv;

void *server_recv(void *arg)
{
    struct message msg_rcv = {0};
    do
    {
        memset(msg_rcv.msg_text,0,BUFFER_SIZE);
        if(msgrcv(qid_rcv,(void *)&msg_rcv,BUFFER_SIZE,0,0) < 0)
        {
            perror("msgrcv./n");
            exit(1);
        }

        printf("The message from process %d:%s\n",(int)msg_rcv.msg_type,msg_rcv.msg_text); 

        parse_message(msg_rcv.msg_text);
    }while(strncmp(msg_rcv.msg_text,"quit",4));

    pthread_exit(NULL);
}

int main()
{
    pthread_t thread = 0;
    int res = 0;
    char *pstr = cmd_buf;
            
    if((res = InitMessage()) != 0){
        printf("Create Msg failed.\n");
    }
    res = pthread_create(&thread,NULL,server_recv,(void *)thread);
    if(res != 0)
    {
        printf("Create thread failed.\n");
        exit(res);
    }
    
    while(1)
    {  

        memset(pstr,0,CMD_BUF_SIZE + 1);
        printf(CMD_PROMPT);
        if(get_cmd(pstr) > 0)
        {
            if(0 == strncmp(pstr,"quit",4)){
                break;
            }
            
            exec_cmdline(pstr);
        }
    }
    ExitMessage();
    pthread_join(thread,NULL);
    
    return 0;
}